package com.fintech.third.utils.wechat;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.codec.binary.Hex;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONObject;
import com.marvels.common.utils.MarvelsLogUtil;





public class WeChatUtil {
	
	/**
	 * 
	* @Title: getRandomStringByLength 
	* @Description: 生成随机串
	 */
	public static String getRandomStringByLength(int length) {  
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        String baseZM = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < length; i++) {
        	if(i==0){//限制为字母开头
        		int number = random.nextInt(baseZM.length());  
                sb.append(baseZM.charAt(number));
                continue;
        	}
            int number = random.nextInt(base.length());  
            sb.append(base.charAt(number));  
        }  
        return sb.toString();  
    } 

	
	public static int getSecondTimestamp(){  
    	Date date = new Date();
        String timestamp = String.valueOf(date.getTime());  
        int length = timestamp.length();  
        if (length > 3) {  
            return Integer.valueOf(timestamp.substring(0,length-3));  
        } else {  
            return 0;  
        }  
    }  
	
	/**
	 * 
	* @Title: getWechatSign 
	* @Description: 获取微信签名 
	 */
	public static String getWechatSign(Map<String, Object>param,String key){
		List<String> list = new ArrayList<String>();
		for(String key1:(Set<String>)param.keySet()){
			list.add(key1);
		}
		Collections.sort(list);
		String a = "";
		for(String key2:list){
			a +=key2+"="+param.get(key2)+"&";
		}
		a += "key="+key;
		MarvelsLogUtil.getInstance().info("加密前组合的字串："+a);
		System.out.println(a);
		String str = getMD5(a).toUpperCase();
		MarvelsLogUtil.getInstance().info("加密后的加密串："+str);
		return str;
	}
	
	public static String getMD5(String str) {
        MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
	        md.update(str.getBytes());
	        return byteToHexString(md.digest());
	        //return new BigInteger(1, md.digest()).toString(16);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private static String byteToHexString(byte[] bytes) {
		return String.valueOf(Hex.encodeHex(bytes));
	}
	
	
	/**  
     * Map转换成Xml  
     * @param map  
     * @return  
     */  
    public static String map2Xmlstring(Map<String, Object> param){  
        StringBuffer sb = new StringBuffer("");  
        sb.append("<xml>");  
          
        Set<String> set = param.keySet();  
        for(Iterator<String> it=set.iterator(); it.hasNext();){  
            String key = it.next();  
            Object value = param.get(key);  
            sb.append("<").append(key).append(">");  
            sb.append(value);  
            sb.append("</").append(key).append(">");  
        }  
        sb.append("</xml>");  
        return sb.toString();  
    } 
    
    /**  
     * Xml string转换成Map  
     * @param xmlStr  
     * @return  
     */  
    public static JSONObject xmlString2Json(String xmlStr){  
    	JSONObject data = new JSONObject(); 
        Document doc;  
        try {  
            doc = DocumentHelper.parseText(xmlStr);  
            Element el = doc.getRootElement();  
            data = recGetXmlElementValueByDJson(el,data);  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        }  
        return data;  
    }  
    
    
    /**  
     * 循环解析xml成Map  
     * @param ele  
     * @param map  
     * @return  
     */  
    @SuppressWarnings({ "unchecked" })  
    private static JSONObject recGetXmlElementValueByDJson(Element ele, JSONObject map){  
        List<Element> eleList = ele.elements();  
        if (eleList.size() == 0) {  
            map.put(ele.getName(), ele.getTextTrim());  
            return map;  
        } else {  
            for (Iterator<Element> iter = eleList.iterator(); iter.hasNext();) {  
                Element innerEle = iter.next();  
                recGetXmlElementValueByDJson(innerEle, map);  
            }  
            return map;  
        }  
    } 
}
